package com.wjv.example.spbt.shiro.config;

import com.wjv.example.spbt.shiro.model.Permission;
import com.wjv.example.spbt.shiro.model.Role;
import com.wjv.example.spbt.shiro.model.UserInfo;
import com.wjv.example.spbt.shiro.service.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>Title: CustomRealm</p>
 *
 * @author wjv
 * @date 2021/7/5 13:27
 */
public class  CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserServiceImpl userService;

    /**
     * 权限配置
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取登录用户名
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();

        // 添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : userInfo.getRoleList()) {
            // 添加角色
            simpleAuthorizationInfo.addRole(role.getRole());
            // 添加权限
            Set<String> pset = role.getPermissions().stream().map(Permission::getPermission).collect(Collectors.toSet());
            simpleAuthorizationInfo.setStringPermissions(pset);
        }
        return simpleAuthorizationInfo;
    }

    /**
     *  认证配置
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (Objects.isNull(authenticationToken.getPrincipal())) {
            return null;
        }

        // 获取用户信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserInfo user = userService.getUserInfo(token.getUsername());
        if (user == null) {
            throw new AuthenticationException("账户/密码错误");
        }

        // 这里验证authenticationToken和simpleAuthenticationInfo的信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, token.getPassword(), getName());
        return simpleAuthenticationInfo;
    }
}
